<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>银行卡管理系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#4080FF',
            tertiary: '#86B4FF',
            dark: '#0E42D2',
            light: '#E8F3FF',
            success: '#00B42A',
            warning: '#FF7D00',
            danger: '#F53F3F',
            info: '#86909C'
          },
          fontFamily: {
            inter: ['Inter', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(22, 93, 255, 0.1);
      }
      .btn-hover {
        @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-0.5;
      }
      .input-focus {
        @apply focus:ring-2 focus:ring-primary/30 focus:border-primary;
      }
      .table-hover-row {
        @apply transition-all duration-200 hover:bg-primary/5;
      }
      .badge {
        @apply px-2 py-0.5 rounded-full text-xs font-medium;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-gray-800 min-h-screen flex flex-col">
  <!-- 顶部导航 -->
  <header class="bg-primary text-white shadow-md z-10 sticky top-0">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
      <div class="flex items-center space-x-2">
        <i class="fa fa-credit-card text-2xl"></i>
        <h1 class="text-xl md:text-2xl font-bold">银行卡管理系统</h1>
      </div>
      <div class="flex items-center space-x-4">
        <button id="refreshBtn" class="flex items-center space-x-1 text-sm bg-white/10 hover:bg-white/20 transition-colors px-3 py-1.5 rounded-lg">
          <i class="fa fa-refresh"></i>
          <span>刷新</span>
        </button>
        <button id="exportBtn" class="flex items-center space-x-1 text-sm bg-white px-3 py-1.5 rounded-lg text-primary font-medium btn-hover">
          <i class="fa fa-download"></i>
          <span>导出CSV</span>
        </button>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-grow container mx-auto px-4 py-6">
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
      <div class="bg-white rounded-xl p-4 card-shadow border-l-4 border-primary">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm">总银行卡数</p>
            <h3 id="totalCards" class="text-2xl font-bold mt-1">0</h3>
            <p class="text-success text-xs mt-1"><i class="fa fa-arrow-up"></i> 较上月增长 5.2%</p>
          </div>
          <div class="bg-primary/10 p-3 rounded-lg">
            <i class="fa fa-credit-card text-primary text-xl"></i>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl p-4 card-shadow border-l-4 border-secondary">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm">活跃卡数</p>
            <h3 id="activeCards" class="text-2xl font-bold mt-1">0</h3>
            <p class="text-success text-xs mt-1"><i class="fa fa-arrow-up"></i> 较上月增长 3.8%</p>
          </div>
          <div class="bg-secondary/10 p-3 rounded-lg">
            <i class="fa fa-check-circle text-secondary text-xl"></i>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl p-4 card-shadow border-l-4 border-warning">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm">挂失卡数</p>
            <h3 id="frozenCards" class="text-2xl font-bold mt-1">0</h3>
            <p class="text-danger text-xs mt-1"><i class="fa fa-arrow-up"></i> 较上月增长 1.5%</p>
          </div>
          <div class="bg-warning/10 p-3 rounded-lg">
            <i class="fa fa-lock text-warning text-xl"></i>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl p-4 card-shadow border-l-4 border-success">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm">总余额 (元)</p>
            <h3 id="totalBalance" class="text-2xl font-bold mt-1">0.00</h3>
            <p class="text-success text-xs mt-1"><i class="fa fa-arrow-up"></i> 较上月增长 7.3%</p>
          </div>
          <div class="bg-success/10 p-3 rounded-lg">
            <i class="fa fa-rmb text-success text-xl"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作区域 -->
    <div class="bg-white rounded-xl p-4 mb-6 card-shadow">
      <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4 gap-4">
        <div class="flex items-center space-x-2">
          <button id="addCardBtn" class="bg-primary hover:bg-dark text-white px-4 py-2 rounded-lg flex items-center space-x-2 btn-hover">
            <i class="fa fa-plus"></i>
            <span>添加银行卡</span>
          </button>
          <button id="batchDeleteBtn" class="bg-danger hover:bg-red-600 text-white px-4 py-2 rounded-lg flex items-center space-x-2 btn-hover opacity-50 cursor-not-allowed">
            <i class="fa fa-trash"></i>
            <span>批量删除</span>
          </button>
        </div>

        <div class="w-full md:w-auto flex items-center space-x-2">
          <div class="relative w-full md:w-64">
            <input type="text" id="searchInput" placeholder="搜索卡号/客户编号" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg input-focus outline-none transition-all">
            <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </div>
          <select id="statusFilter" class="border border-gray-300 rounded-lg px-3 py-2 input-focus outline-none">
            <option value="all">全部状态</option>
            <option value="active">正常</option>
            <option value="frozen">已挂失</option>
          </select>
        </div>
      </div>

      <!-- 数据图表 -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div class="lg:col-span-2 bg-light rounded-lg p-4">
          <h3 class="font-medium mb-3">存款类型分布</h3>
          <div class="h-64">
            <canvas id="depositChart"></canvas>
          </div>
        </div>
        <div class="bg-light rounded-lg p-4">
          <h3 class="font-medium mb-3">账户状态统计</h3>
          <div class="h-64">
            <canvas id="statusChart"></canvas>
          </div>
        </div>
      </div>
    </div>

    <!-- 银行卡列表 -->
    <div class="bg-white rounded-xl overflow-hidden card-shadow">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="bg-gray-50 text-left">
              <th class="py-3 px-4 w-12">
                <input type="checkbox" id="selectAll" class="rounded border-gray-300 text-primary focus:ring-primary">
              </th>
              <th class="py-3 px-4 font-semibold">卡号</th>
              <th class="py-3 px-4 font-semibold">存款类型</th>
              <th class="py-3 px-4 font-semibold">开户日期</th>
              <th class="py-3 px-4 font-semibold">开户金额 (元)</th>
              <th class="py-3 px-4 font-semibold">当前余额 (元)</th>
              <th class="py-3 px-4 font-semibold">客户编号</th>
              <th class="py-3 px-4 font-semibold">状态</th>
              <th class="py-3 px-4 font-semibold">操作</th>
            </tr>
          </thead>
          <tbody id="cardTableBody">
            <!-- 表格内容会通过JavaScript动态生成 -->
            <tr>
              <td colspan="9" class="py-10 text-center text-gray-500">
                <div class="flex flex-col items-center">
                  <i class="fa fa-credit-card text-4xl text-gray-300 mb-3"></i>
                  <p>暂无银行卡数据</p>
                  <button id="addFirstCardBtn" class="mt-3 bg-primary text-white px-4 py-2 rounded-lg btn-hover">
                    添加第一张银行卡
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-4 py-3 flex justify-between items-center border-t border-gray-200">
        <div class="text-sm text-gray-600">
          显示 <span id="startIndex">0</span>-<span id="endIndex">0</span> 条，共 <span id="totalCount">0</span> 条
        </div>
        <div class="flex items-center space-x-1">
          <button class="px-3 py-1 rounded border border-gray-300 bg-white text-gray-600 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" id="prevPage" disabled>
            <i class="fa fa-angle-left"></i>
          </button>
          <div class="flex">
            <button class="px-3 py-1 rounded border border-primary bg-primary text-white">1</button>
          </div>
          <button class="px-3 py-1 rounded border border-gray-300 bg-white text-gray-600 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" id="nextPage" disabled>
            <i class="fa fa-angle-right"></i>
          </button>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-gray-800 text-white py-6 mt-8">
    <div class="container mx-auto px-4">
      <div class="flex flex-col md:flex-row justify-between items-center">
        <div class="mb-4 md:mb-0">
          <div class="flex items-center space-x-2">
            <i class="fa fa-credit-card text-xl"></i>
            <span class="font-bold text-lg">银行卡管理系统</span>
          </div>
          <p class="text-gray-400 text-sm mt-1">安全、高效地管理您的银行卡信息</p>
        </div>
        <div class="flex space-x-6">
          <a href="#" class="text-gray-400 hover:text-white transition-colors">
            <i class="fa fa-question-circle"></i>
            <span class="ml-1">帮助中心</span>
          </a>
          <a href="#" class="text-gray-400 hover:text-white transition-colors">
            <i class="fa fa-shield"></i>
            <span class="ml-1">安全中心</span>
          </a>
          <a href="#" class="text-gray-400 hover:text-white transition-colors">
            <i class="fa fa-phone"></i>
            <span class="ml-1">联系我们</span>
          </a>
        </div>
      </div>
      <div class="border-t border-gray-700 mt-6 pt-6 text-center text-gray-400 text-sm">
        © 2025 银行卡管理系统 版权所有
      </div>
    </div>
  </footer>

  <!-- 添加/编辑银行卡模态框 -->
  <div id="cardModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
      <div class="p-5 border-b border-gray-200 flex justify-between items-center">
        <h3 id="modalTitle" class="text-xl font-bold">添加银行卡</h3>
        <button id="closeModal" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times text-xl"></i>
        </button>
      </div>
      <div class="p-5">
        <form id="cardForm">
          <input type="hidden" id="cardId">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div>
              <label for="cardNumber" class="block text-sm font-medium text-gray-700 mb-1">卡号 <span class="text-danger">*</span></label>
              <input type="text" id="cardNumber" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请输入卡号" required>
              <p id="cardNumberError" class="text-danger text-xs mt-1 hidden">卡号格式不正确</p>
            </div>
            <div>
              <label for="depositType" class="block text-sm font-medium text-gray-700 mb-1">存款类型 <span class="text-danger">*</span></label>
              <select id="depositType" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" required>
                <option value="">请选择</option>
                <option value="活期存款">活期存款</option>
                <option value="定期存款">定期存款</option>
                <option value="通知存款">通知存款</option>
                <option value="协定存款">协定存款</option>
              </select>
            </div>
            <div>
              <label for="openDate" class="block text-sm font-medium text-gray-700 mb-1">开户日期 <span class="text-danger">*</span></label>
              <input type="date" id="openDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" required>
            </div>
            <div>
              <label for="initialAmount" class="block text-sm font-medium text-gray-700 mb-1">开户金额 (元) <span class="text-danger">*</span></label>
              <input type="number" id="initialAmount" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请输入开户金额" min="0.01" step="0.01" required>
            </div>
            <div>
              <label for="currentBalance" class="block text-sm font-medium text-gray-700 mb-1">当前余额 (元) <span class="text-danger">*</span></label>
              <input type="number" id="currentBalance" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请输入当前余额" min="0.01" step="0.01" required>
            </div>
            <div>
              <label for="customerId" class="block text-sm font-medium text-gray-700 mb-1">客户编号 <span class="text-danger">*</span></label>
              <input type="text" id="customerId" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请输入客户编号" required>
            </div>
            <div>
              <label for="cardPassword" class="block text-sm font-medium text-gray-700 mb-1">银行卡密码 <span class="text-danger">*</span></label>
              <div class="relative">
                <input type="password" id="cardPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请输入6位数字密码" required>
                <button type="button" id="togglePassword" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600">
                  <i class="fa fa-eye-slash"></i>
                </button>
              </div>
              <p id="passwordError" class="text-danger text-xs mt-1 hidden">密码必须为6位数字</p>
            </div>
            <div>
              <label for="cardStatus" class="block text-sm font-medium text-gray-700 mb-1">卡片状态</label>
              <select id="cardStatus" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none">
                <option value="active">正常</option>
                <option value="frozen">已挂失</option>
              </select>
            </div>
          </div>

          <div class="flex justify-end space-x-3 mt-6">
            <button type="button" id="cancelForm" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">取消</button>
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-dark transition-colors btn-hover">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- 密码修改模态框 -->
  <div id="passwordModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl w-full max-w-md">
      <div class="p-5 border-b border-gray-200 flex justify-between items-center">
        <h3 class="text-xl font-bold">修改密码</h3>
        <button id="closePasswordModal" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times text-xl"></i>
        </button>
      </div>
      <div class="p-5">
        <form id="passwordForm">
          <input type="hidden" id="passwordCardId">
          <div class="mb-4">
            <label for="oldPassword" class="block text-sm font-medium text-gray-700 mb-1">原密码 <span class="text-danger">*</span></label>
            <input type="password" id="oldPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请输入原密码" required>
          </div>
          <div class="mb-4">
            <label for="newPassword" class="block text-sm font-medium text-gray-700 mb-1">新密码 <span class="text-danger">*</span></label>
            <input type="password" id="newPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请输入新密码" required>
            <p id="newPasswordError" class="text-danger text-xs mt-1 hidden">密码必须为6位数字</p>
          </div>
          <div class="mb-4">
            <label for="confirmPassword" class="block text-sm font-medium text-gray-700 mb-1">确认新密码 <span class="text-danger">*</span></label>
            <input type="password" id="confirmPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg input-focus outline-none" placeholder="请再次输入新密码" required>
            <p id="confirmPasswordError" class="text-danger text-xs mt-1 hidden">两次输入的密码不一致</p>
          </div>

          <div class="flex justify-end space-x-3 mt-6">
            <button type="button" id="cancelPasswordForm" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">取消</button>
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-dark transition-colors btn-hover">确认修改</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- 确认删除模态框 -->
  <div id="confirmModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl w-full max-w-md">
      <div class="p-5 border-b border-gray-200">
        <h3 class="text-xl font-bold">确认删除</h3>
      </div>
      <div class="p-5">
        <p id="confirmMessage">您确定要删除该银行卡吗？此操作不可撤销。</p>
        <div class="flex justify-end space-x-3 mt-6">
          <button id="cancelDelete" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">取消</button>
          <button id="confirmDelete" class="px-4 py-2 bg-danger text-white rounded-lg hover:bg-red-600 transition-colors btn-hover">确认删除</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 挂失/解挂模态框 -->
  <div id="statusModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl w-full max-w-md">
      <div class="p-5 border-b border-gray-200">
        <h3 id="statusModalTitle" class="text-xl font-bold">挂失银行卡</h3>
      </div>
      <div class="p-5">
        <p id="statusMessage">您确定要挂失该银行卡吗？挂失后卡片将无法正常使用。</p>
        <div class="flex justify-end space-x-3 mt-6">
          <button id="cancelStatusChange" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">取消</button>
          <button id="confirmStatusChange" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-dark transition-colors btn-hover">确认</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 通知提示 -->
  <div id="notification" class="fixed top-4 right-4 max-w-sm bg-white rounded-lg shadow-lg p-4 transform translate-x-full transition-transform duration-300 flex items-start z-50">
    <div id="notificationIcon" class="mr-3 text-primary">
      <i class="fa fa-info-circle text-xl"></i>
    </div>
    <div class="flex-1">
      <h4 id="notificationTitle" class="font-medium">通知标题</h4>
      <p id="notificationMessage" class="text-sm text-gray-600 mt-1">通知内容将显示在这里...</p>
    </div>
    <button id="closeNotification" class="text-gray-400 hover:text-gray-600 ml-2">
      <i class="fa fa-times"></i>
    </button>
  </div>

  <script>
    // 模拟数据
    let bankCards = [
      {
        id: 1,
        cardNumber: '6222021234567890123',
        depositType: '活期存款',
        openDate: '2023-05-15',
        initialAmount: 10000.00,
        currentBalance: 15230.75,
        password: '123456',
        status: 'active',
        customerId: 'CUST10001'
      },
      {
        id: 2,
        cardNumber: '6222032345678901234',
        depositType: '定期存款',
        openDate: '2023-08-20',
        initialAmount: 50000.00,
        currentBalance: 51250.00,
        password: '234567',
        status: 'active',
        customerId: 'CUST10002'
      },
      {
        id: 3,
        cardNumber: '6222043456789012345',
        depositType: '通知存款',
        openDate: '2024-01-10',
        initialAmount: 20000.00,
        currentBalance: 20100.00,
        password: '345678',
        status: 'frozen',
        customerId: 'CUST10003'
      }
    ];

    let selectedCardId = null;
    let selectedCardIds = [];
    let currentPage = 1;
    let cardsPerPage = 5;

    // DOM 元素
    const cardTableBody = document.getElementById('cardTableBody');
    const addCardBtn = document.getElementById('addCardBtn');
    const addFirstCardBtn = document.getElementById('addFirstCardBtn');
    const cardModal = document.getElementById('cardModal');
    const closeModal = document.getElementById('closeModal');
    const modalTitle = document.getElementById('modalTitle');
    const cardForm = document.getElementById('cardForm');
    const cardNumber = document.getElementById('cardNumber');
    const cardNumberError = document.getElementById('cardNumberError');
    const depositType = document.getElementById('depositType');
    const openDate = document.getElementById('openDate');
    const initialAmount = document.getElementById('initialAmount');
    const currentBalance = document.getElementById('currentBalance');
    const cardPassword = document.getElementById('cardPassword');
    const passwordError = document.getElementById('passwordError');
    const customerId = document.getElementById('customerId');
    const cardStatus = document.getElementById('cardStatus');
    const cancelForm = document.getElementById('cancelForm');
    const passwordModal = document.getElementById('passwordModal');
    const closePasswordModal = document.getElementById('closePasswordModal');
    const passwordForm = document.getElementById('passwordForm');
    const passwordCardId = document.getElementById('passwordCardId');
    const oldPassword = document.getElementById('oldPassword');
    const newPassword = document.getElementById('newPassword');
    const newPasswordError = document.getElementById('newPasswordError');
    const confirmPassword = document.getElementById('confirmPassword');
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    const cancelPasswordForm = document.getElementById('cancelPasswordForm');
    const confirmModal = document.getElementById('confirmModal');
    const confirmMessage = document.getElementById('confirmMessage');
    const cancelDelete = document.getElementById('cancelDelete');
    const confirmDelete = document.getElementById('confirmDelete');
    const statusModal = document.getElementById('statusModal');
    const statusModalTitle = document.getElementById('statusModalTitle');
    const statusMessage = document.getElementById('statusMessage');
    const cancelStatusChange = document.getElementById('cancelStatusChange');
    const confirmStatusChange = document.getElementById('confirmStatusChange');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    const selectAll = document.getElementById('selectAll');
    const searchInput = document.getElementById('searchInput');
    const statusFilter = document.getElementById('statusFilter');
    const refreshBtn = document.getElementById('refreshBtn');
    const exportBtn = document.getElementById('exportBtn');
    const prevPage = document.getElementById('prevPage');
    const nextPage = document.getElementById('nextPage');
    const startIndex = document.getElementById('startIndex');
    const endIndex = document.getElementById('endIndex');
    const totalCount = document.getElementById('totalCount');
    const totalCards = document.getElementById('totalCards');
    const activeCards = document.getElementById('activeCards');
    const frozenCards = document.getElementById('frozenCards');
    const totalBalance = document.getElementById('totalBalance');
    const notification = document.getElementById('notification');
    const notificationIcon = document.getElementById('notificationIcon');
    const notificationTitle = document.getElementById('notificationTitle');
    const notificationMessage = document.getElementById('notificationMessage');
    const closeNotification = document.getElementById('closeNotification');
    const togglePassword = document.getElementById('togglePassword');

    // 初始化页面
    function initPage() {
      updateTable();
      updateStatistics();
      initCharts();
      setupEventListeners();
    }

    // 设置事件监听器
    function setupEventListeners() {
      // 添加银行卡
      addCardBtn.addEventListener('click', openAddCardModal);
      addFirstCardBtn.addEventListener('click', openAddCardModal);

      // 关闭模态框
      closeModal.addEventListener('click', closeCardModal);
      cancelForm.addEventListener('click', closeCardModal);

      // 表单提交
      cardForm.addEventListener('submit', handleCardFormSubmit);

      // 密码修改
      passwordForm.addEventListener('submit', handlePasswordFormSubmit);
      closePasswordModal.addEventListener('click', closePasswordModalFunc);
      cancelPasswordForm.addEventListener('click', closePasswordModalFunc);

      // 删除确认
      cancelDelete.addEventListener('click', closeConfirmModal);
      confirmDelete.addEventListener('click', handleDeleteCard);

      // 状态变更
      cancelStatusChange.addEventListener('click', closeStatusModal);
      confirmStatusChange.addEventListener('click', handleStatusChange);

      // 批量操作
      selectAll.addEventListener('change', handleSelectAll);
      batchDeleteBtn.addEventListener('click', handleBatchDelete);

      // 搜索和过滤
      searchInput.addEventListener('input', debounce(updateTable, 300));
      statusFilter.addEventListener('change', updateTable);

      // 刷新和导出
      refreshBtn.addEventListener('click', refreshTable);
      exportBtn.addEventListener('click', exportToCSV);

      // 分页
      prevPage.addEventListener('click', goToPrevPage);
      nextPage.addEventListener('click', goToNextPage);

      // 关闭通知
      closeNotification.addEventListener('click', hideNotification);

      // 密码显示切换
      togglePassword.addEventListener('click', togglePasswordVisibility);

      // 表单验证
      cardNumber.addEventListener('input', validateCardNumber);
      cardPassword.addEventListener('input', validatePassword);
      newPassword.addEventListener('input', validateNewPassword);
      confirmPassword.addEventListener('input', validateConfirmPassword);
    }

    // 防抖函数
    function debounce(func, delay) {
      let timeout;
      return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), delay);
      };
    }

    // 初始化图表
    function initCharts() {
      // 存款类型分布图表
      const depositCtx = document.getElementById('depositChart').getContext('2d');
      const depositData = getDepositTypeData();

      new Chart(depositCtx, {
        type: 'bar',
        data: {
          labels: depositData.labels,
          datasets: [{
            label: '账户数量',
            data: depositData.counts,
            backgroundColor: [
              'rgba(22, 93, 255, 0.7)',
              'rgba(64, 128, 255, 0.7)',
              'rgba(134, 180, 255, 0.7)',
              'rgba(232, 243, 255, 0.7)'
            ],
            borderColor: [
              'rgba(22, 93, 255, 1)',
              'rgba(64, 128, 255, 1)',
              'rgba(134, 180, 255, 1)',
              'rgba(232, 243, 255, 1)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                precision: 0
              }
            }
          }
        }
      });

      // 账户状态统计图表
      const statusCtx = document.getElementById('statusChart').getContext('2d');
      const activeCount = bankCards.filter(card => card.status === 'active').length;
      const frozenCount = bankCards.filter(card => card.status === 'frozen').length;

      new Chart(statusCtx, {
        type: 'doughnut',
        data: {
          labels: ['正常', '已挂失'],
          datasets: [{
            data: [activeCount, frozenCount],
            backgroundColor: [
              'rgba(0, 180, 42, 0.7)',
              'rgba(245, 63, 63, 0.7)'
            ],
            borderColor: [
              'rgba(0, 180, 42, 1)',
              'rgba(245, 63, 63, 1)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'bottom'
            }
          }
        }
      });
    }

    // 获取存款类型数据
    function getDepositTypeData() {
      const types = ['活期存款', '定期存款', '通知存款', '协定存款'];
      const counts = types.map(type => bankCards.filter(card => card.depositType === type).length);

      return {
        labels: types,
        counts: counts
      };
    }

    // 更新统计信息
    function updateStatistics() {
      totalCards.textContent = bankCards.length;
      activeCards.textContent = bankCards.filter(card => card.status === 'active').length;
      frozenCards.textContent = bankCards.filter(card => card.status === 'frozen').length;
      totalBalance.textContent = bankCards.reduce((sum, card) => sum + card.currentBalance, 0).toFixed(2);
    }

    // 更新表格
    function updateTable() {
      const filteredCards = filterCards();
      const totalPages = Math.ceil(filteredCards.length / cardsPerPage);

      // 确保当前页在有效范围内
      if (currentPage > totalPages && totalPages > 0) {
        currentPage = totalPages;
        updateTable();
        return;
      }

      const startIdx = (currentPage - 1) * cardsPerPage;
      const endIdx = Math.min(startIdx + cardsPerPage, filteredCards.length);
      const paginatedCards = filteredCards.slice(startIdx, endIdx);

      // 更新表格内容
      if (paginatedCards.length === 0) {
        cardTableBody.innerHTML = `
          <tr>
            <td colspan="9" class="py-10 text-center text-gray-500">
              <div class="flex flex-col items-center">
                <i class="fa fa-credit-card text-4xl text-gray-300 mb-3"></i>
                <p>没有找到匹配的银行卡数据</p>
                <button id="addFirstCardBtn" class="mt-3 bg-primary text-white px-4 py-2 rounded-lg btn-hover">
                  添加银行卡
                </button>
              </div>
            </td>
          </tr>
        `;
        addFirstCardBtn.addEventListener('click', openAddCardModal);
      } else {
        cardTableBody.innerHTML = paginatedCards.map(card => `
          <tr class="border-b border-gray-200 table-hover-row">
            <td class="py-3 px-4">
              <input type="checkbox" class="card-checkbox rounded border-gray-300 text-primary focus:ring-primary" data-id="${card.id}">
            </td>
            <td class="py-3 px-4 font-medium">${formatCardNumber(card.cardNumber)}</td>
            <td class="py-3 px-4">${card.depositType}</td>
            <td class="py-3 px-4">${card.openDate}</td>
            <td class="py-3 px-4">${card.initialAmount.toFixed(2)}</td>
            <td class="py-3 px-4 font-medium">${card.currentBalance.toFixed(2)}</td>
            <td class="py-3 px-4">${card.customerId}</td>
            <td class="py-3 px-4">
              <span class="badge ${card.status === 'active' ? 'bg-success/10 text-success' : 'bg-danger/10 text-danger'}">
                ${card.status === 'active' ? '正常' : '已挂失'}
              </span>
            </td>
            <td class="py-3 px-4">
              <div class="flex space-x-2">
                <button class="edit-btn text-primary hover:text-dark transition-colors" data-id="${card.id}">
                  <i class="fa fa-edit"></i>
                </button>
                <button class="password-btn text-secondary hover:text-primary transition-colors" data-id="${card.id}">
                  <i class="fa fa-key"></i>
                </button>
                <button class="status-btn ${card.status === 'active' ? 'text-warning hover:text-orange-600' : 'text-success hover:text-green-600'} transition-colors" data-id="${card.id}">
                  ${card.status === 'active' ? '<i class="fa fa-lock"></i>' : '<i class="fa fa-unlock"></i>'}
                </button>
                <button class="delete-btn text-danger hover:text-red-600 transition-colors" data-id="${card.id}">
                  <i class="fa fa-trash"></i>
                </button>
              </div>
            </td>
          </tr>
        `).join('');

        // 添加事件监听器
        document.querySelectorAll('.edit-btn').forEach(btn => {
          btn.addEventListener('click', () => {
            const id = parseInt(btn.getAttribute('data-id'));
            openEditCardModal(id);
          });
        });

        document.querySelectorAll('.password-btn').forEach(btn => {
          btn.addEventListener('click', () => {
            const id = parseInt(btn.getAttribute('data-id'));
            openPasswordModal(id);
          });
        });

        document.querySelectorAll('.status-btn').forEach(btn => {
          btn.addEventListener('click', () => {
            const id = parseInt(btn.getAttribute('data-id'));
            openStatusModal(id);
          });
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
          btn.addEventListener('click', () => {
            const id = parseInt(btn.getAttribute('data-id'));
            openConfirmModal(id);
          });
        });

        document.querySelectorAll('.card-checkbox').forEach(checkbox => {
          checkbox.addEventListener('change', handleCardSelection);
        });
      }

      // 更新分页信息
      startIndex.textContent = filteredCards.length > 0 ? startIdx + 1 : 0;
      endIndex.textContent = endIdx;
      totalCount.textContent = filteredCards.length;

      // 更新分页按钮状态
      prevPage.disabled = currentPage === 1;
      nextPage.disabled = endIdx >= filteredCards.length;

      // 更新批量删除按钮状态
      updateBatchDeleteBtn();
    }

    // 过滤银行卡
    function filterCards() {
      const searchTerm = searchInput.value.toLowerCase().trim();
      const status = statusFilter.value;

      return bankCards.filter(card => {
        const matchesSearch =
          card.cardNumber.toLowerCase().includes(searchTerm) ||
          card.customerId.toLowerCase().includes(searchTerm);

        const matchesStatus = status === 'all' || card.status === status;

        return matchesSearch && matchesStatus;
      });
    }

    // 格式化卡号
    function formatCardNumber(cardNumber) {
      if (!cardNumber) return '';
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ');
    }

    // 打开添加银行卡模态框
    function openAddCardModal() {
      modalTitle.textContent = '添加银行卡';
      cardForm.reset();
      document.getElementById('cardId').value = '';
      cardModal.classList.remove('hidden');
      cardNumber.focus();
    }

    // 关闭添加/编辑银行卡模态框
    function closeCardModal() {
      cardModal.classList.add('hidden');
      // 清除错误提示
      cardNumberError.classList.add('hidden');
      passwordError.classList.add('hidden');
    }

    // 打开编辑银行卡模态框
    function openEditCardModal(id) {
      const card = bankCards.find(card => card.id === id);
      if (!card) return;

      modalTitle.textContent = '编辑银行卡';
      document.getElementById('cardId').value = card.id;
      cardNumber.value = card.cardNumber;
      depositType.value = card.depositType;
      openDate.value = card.openDate;
      initialAmount.value = card.initialAmount;
      currentBalance.value = card.currentBalance;
      cardPassword.value = card.password;
      customerId.value = card.customerId;
      cardStatus.value = card.status;

      cardModal.classList.remove('hidden');
      cardNumber.focus();
    }

    // 处理银行卡表单提交
    function handleCardFormSubmit(e) {
      e.preventDefault();

      // 验证表单
      if (!validateCardForm()) return;

      const id = document.getElementById('cardId').value;
      const cardData = {
        cardNumber: cardNumber.value,
        depositType: depositType.value,
        openDate: openDate.value,
        initialAmount: parseFloat(initialAmount.value),
        currentBalance: parseFloat(currentBalance.value),
        password: cardPassword.value,
        customerId: customerId.value,
        status: cardStatus.value
      };

      if (id) {
        // 更新现有银行卡
        const index = bankCards.findIndex(card => card.id === parseInt(id));
        if (index !== -1) {
          bankCards[index] = { ...bankCards[index], ...cardData };
          showNotification('成功', '银行卡信息已更新', 'success');
        }
      } else {
        // 添加新银行卡
        const newId = bankCards.length > 0 ? Math.max(...bankCards.map(card => card.id)) + 1 : 1;
        bankCards.push({ id: newId, ...cardData });
        showNotification('成功', '银行卡添加成功', 'success');
      }

      closeCardModal();
      updateTable();
      updateStatistics();
      initCharts();
    }

    // 验证银行卡表单
    function validateCardForm() {
      let isValid = true;

      if (!validateCardNumber()) isValid = false;
      if (!validatePassword()) isValid = false;

      return isValid;
    }

    // 验证卡号
    function validateCardNumber() {
      const cardNum = cardNumber.value.trim();
      const cardNumPattern = /^\d{16,19}$/;

      if (!cardNumPattern.test(cardNum)) {
        cardNumberError.classList.remove('hidden');
        return false;
      } else {
        cardNumberError.classList.add('hidden');
        return true;
      }
    }

    // 验证密码
    function validatePassword() {
      const password = cardPassword.value.trim();
      const passwordPattern = /^\d{6}$/;

      if (!passwordPattern.test(password)) {
        passwordError.classList.remove('hidden');
        return false;
      } else {
        passwordError.classList.add('hidden');
        return true;
      }
    }

    // 打开密码修改模态框
    function openPasswordModal(id) {
      const card = bankCards.find(card => card.id === id);
      if (!card) return;

      passwordCardId.value = card.id;
      oldPassword.value = '';
      newPassword.value = '';
      confirmPassword.value = '';

      // 清除错误提示
      newPasswordError.classList.add('hidden');
      confirmPasswordError.classList.add('hidden');

      passwordModal.classList.remove('hidden');
      oldPassword.focus();
    }

    // 关闭密码修改模态框
    function closePasswordModalFunc() {
      passwordModal.classList.add('hidden');
    }

    // 处理密码表单提交
    function handlePasswordFormSubmit(e) {
      e.preventDefault();

      // 验证表单
      if (!validatePasswordForm()) return;

      const id = parseInt(passwordCardId.value);
      const card = bankCards.find(card => card.id === id);

      if (!card) {
        showNotification('错误', '找不到该银行卡', 'error');
        closePasswordModalFunc();
        return;
      }

      if (oldPassword.value !== card.password) {
        showNotification('错误', '原密码不正确', 'error');
        return;
      }

      // 更新密码
      card.password = newPassword.value;
      showNotification('成功', '密码修改成功', 'success');

      closePasswordModalFunc();
    }

    // 验证密码表单
    function validatePasswordForm() {
      let isValid = true;

      if (!validateNewPassword()) isValid = false;
      if (!validateConfirmPassword()) isValid = false;

      return isValid;
    }

    // 验证新密码
    function validateNewPassword() {
      const password = newPassword.value.trim();
      const passwordPattern = /^\d{6}$/;

      if (!passwordPattern.test(password)) {
        newPasswordError.classList.remove('hidden');
        return false;
      } else {
        newPasswordError.classList.add('hidden');
        return true;
      }
    }

    // 验证确认密码
    function validateConfirmPassword() {
      if (newPassword.value !== confirmPassword.value) {
        confirmPasswordError.classList.remove('hidden');
        return false;
      } else {
        confirmPasswordError.classList.add('hidden');
        return true;
      }
    }

    // 打开确认删除模态框
    function openConfirmModal(id) {
      selectedCardId = id;
      confirmMessage.textContent = '您确定要删除该银行卡吗？此操作不可撤销。';
      confirmModal.classList.remove('hidden');
    }

    // 关闭确认删除模态框
    function closeConfirmModal() {
      confirmModal.classList.add('hidden');
      selectedCardId = null;
    }

    // 处理删除银行卡
    function handleDeleteCard() {
      if (selectedCardId === null) return;

      const index = bankCards.findIndex(card => card.id === selectedCardId);
      if (index !== -1) {
        bankCards.splice(index, 1);
        showNotification('成功', '银行卡已删除', 'success');
      }

      closeConfirmModal();
      updateTable();
      updateStatistics();
      initCharts();
    }

    // 打开状态变更模态框
    function openStatusModal(id) {
      const card = bankCards.find(card => card.id === id);
      if (!card) return;

      selectedCardId = id;

      if (card.status === 'active') {
        statusModalTitle.textContent = '挂失银行卡';
        statusMessage.textContent = '您确定要挂失该银行卡吗？挂失后卡片将无法正常使用。';
      } else {
        statusModalTitle.textContent = '解挂银行卡';
        statusMessage.textContent = '您确定要解挂该银行卡吗？解挂后卡片将恢复正常使用。';
      }

      statusModal.classList.remove('hidden');
    }

    // 关闭状态变更模态框
    function closeStatusModal() {
      statusModal.classList.add('hidden');
      selectedCardId = null;
    }

    // 处理状态变更
    function handleStatusChange() {
      if (selectedCardId === null) return;

      const card = bankCards.find(card => card.id === selectedCardId);
      if (!card) return;

      if (card.status === 'active') {
        card.status = 'frozen';
        showNotification('成功', '银行卡已成功挂失', 'success');
      } else {
        card.status = 'active';
        showNotification('成功', '银行卡已成功解挂', 'success');
      }

      closeStatusModal();
      updateTable();
      updateStatistics();
      initCharts();
    }

    // 处理卡片选择
    function handleCardSelection(e) {
      const id = parseInt(e.target.getAttribute('data-id'));

      if (e.target.checked) {
        if (!selectedCardIds.includes(id)) {
          selectedCardIds.push(id);
        }
      } else {
        selectedCardIds = selectedCardIds.filter(cardId => cardId !== id);
      }

      // 更新全选状态
      selectAll.checked = selectedCardIds.length === filterCards().length;

      // 更新批量删除按钮状态
      updateBatchDeleteBtn();
    }

    // 处理全选
    function handleSelectAll() {
      const checkboxes = document.querySelectorAll('.card-checkbox');
      const filteredCardCount = filterCards().length;

      if (selectAll.checked) {
        checkboxes.forEach(checkbox => {
          checkbox.checked = true;
          const id = parseInt(checkbox.getAttribute('data-id'));
          if (!selectedCardIds.includes(id)) {
            selectedCardIds.push(id);
          }
        });
      } else {
        checkboxes.forEach(checkbox => {
          checkbox.checked = false;
        });
        selectedCardIds = [];
      }

      // 更新批量删除按钮状态
      updateBatchDeleteBtn();
    }

    // 更新批量删除按钮状态
    function updateBatchDeleteBtn() {
      if (selectedCardIds.length > 0) {
        batchDeleteBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        batchDeleteBtn.classList.add('btn-hover');
      } else {
        batchDeleteBtn.classList.add('opacity-50', 'cursor-not-allowed');
        batchDeleteBtn.classList.remove('btn-hover');
      }
    }

    // 处理批量删除
    function handleBatchDelete() {
      if (selectedCardIds.length === 0) return;

      if (selectedCardIds.length === 1) {
        openConfirmModal(selectedCardIds[0]);
      } else {
        selectedCardId = null;
        confirmMessage.textContent = `您确定要删除选中的 ${selectedCardIds.length} 张银行卡吗？此操作不可撤销。`;
        confirmModal.classList.remove('hidden');

        // 重写确认删除函数，处理批量删除
        confirmDelete.removeEventListener('click', handleDeleteCard);
        confirmDelete.addEventListener('click', function batchDeleteHandler() {
          // 按ID降序排列，避免删除元素后索引变化
          selectedCardIds.sort((a, b) => b - a);

          selectedCardIds.forEach(id => {
            const index = bankCards.findIndex(card => card.id === id);
            if (index !== -1) {
              bankCards.splice(index, 1);
            }
          });

          showNotification('成功', `已删除 ${selectedCardIds.length} 张银行卡`, 'success');

          selectedCardIds = [];
          closeConfirmModal();
          updateTable();
          updateStatistics();
          initCharts();

          // 恢复原事件监听器
          confirmDelete.removeEventListener('click', batchDeleteHandler);
          confirmDelete.addEventListener('click', handleDeleteCard);
        });
      }
    }

    // 刷新表格
    function refreshTable() {
      searchInput.value = '';
      statusFilter.value = 'all';
      currentPage = 1;
      updateTable();
      showNotification('成功', '数据已刷新', 'info');
    }

    // 导出为CSV
    function exportToCSV() {
      const filteredCards = filterCards();

      if (filteredCards.length === 0) {
        showNotification('提示', '没有数据可导出', 'warning');
        return;
      }

      // 构建CSV内容
      let csvContent = "卡号,存款类型,开户日期,开户金额(元),当前余额(元),客户编号,状态\n";

      filteredCards.forEach(card => {
        const statusText = card.status === 'active' ? '正常' : '已挂失';
        csvContent += `${card.cardNumber},${card.depositType},${card.openDate},${card.initialAmount.toFixed(2)},${card.currentBalance.toFixed(2)},${card.customerId},${statusText}\n`;
      });

      // 创建下载链接
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', `银行卡数据_${new Date().toISOString().slice(0,10)}.csv`);
      link.style.visibility = 'hidden';

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      showNotification('成功', '数据导出成功', 'success');
    }

    // 上一页
    function goToPrevPage() {
      if (currentPage > 1) {
        currentPage--;
        updateTable();
      }
    }

    // 下一页
    function goToNextPage() {
      const filteredCards = filterCards();
      const totalPages = Math.ceil(filteredCards.length / cardsPerPage);

      if (currentPage < totalPages) {
        currentPage++;
        updateTable();
      }
    }

    // 显示通知
    function showNotification(title, message, type = 'info') {
      notificationTitle.textContent = title;
      notificationMessage.textContent = message;

      // 设置图标和颜色
      if (type === 'success') {
        notificationIcon.className = 'mr-3 text-success';
        notificationIcon.innerHTML = '<i class="fa fa-check-circle text-xl"></i>';
      } else if (type === 'error') {
        notificationIcon.className = 'mr-3 text-danger';
        notificationIcon.innerHTML = '<i class="fa fa-times-circle text-xl"></i>';
      } else if (type === 'warning') {
        notificationIcon.className = 'mr-3 text-warning';
        notificationIcon.innerHTML = '<i class="fa fa-exclamation-circle text-xl"></i>';
      } else {
        notificationIcon.className = 'mr-3 text-primary';
        notificationIcon.innerHTML = '<i class="fa fa-info-circle text-xl"></i>';
      }

      // 显示通知
      notification.classList.remove('translate-x-full');

      // 3秒后自动关闭
      setTimeout(hideNotification, 3000);
    }

    // 隐藏通知
    function hideNotification() {
      notification.classList.add('translate-x-full');
    }

    // 切换密码可见性
    function togglePasswordVisibility() {
      const type = cardPassword.getAttribute('type') === 'password' ? 'text' : 'password';
      cardPassword.setAttribute('type', type);

      // 切换图标
      const icon = togglePassword.querySelector('i');
      if (type === 'text') {
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
      } else {
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
      }
    }

    // 初始化页面
    document.addEventListener('DOMContentLoaded', initPage);
  </script>
</body>
</html>    